package com.fengycx.service.impl;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengycx.constants.Constants;
import com.fengycx.constants.GlobalExceptionCode;
import com.fengycx.feign.AppLoginApi;
import com.fengycx.mapper.DriverMapper;
import com.fengycx.pojo.domain.*;
import com.fengycx.pojo.dto.DriverAuthenticDto;
import com.fengycx.pojo.param.AppLoginApiParam;
import com.fengycx.pojo.properties.DriverAppRegisterProp;
import com.fengycx.result.R;
import com.fengycx.service.IDriverService;
import com.fengycx.service.IDriverSettingService;
import com.fengycx.service.IDriverSummaryService;
import com.fengycx.service.IDriverWalletService;
import com.fengycx.template.WechatTemplate;
import com.fengycx.utils.AssertUtil;
import com.fengycx.utils.BitStatesUtil;
import com.fengycx.utils.NameUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;


/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author Cino
 * @since 2024-02-19
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {

    @Autowired
    private IDriverSummaryService driverSummaryService;
    @Autowired
    private IDriverWalletService driverWalletService;
    @Autowired
    private IDriverSettingService driverSettingService;
    @Autowired
    private WechatTemplate wechatTemplate;
    @Autowired
    private AppLoginApi appLoginApi;



    @Override
    @GlobalTransactional(name = "driver-wechat-register",rollbackFor = Exception.class)
    public void code2OpenId(String  appRegisterCode) {
//        String getOpenIdCode = appRegisterCode.getGetOpenIdCode();
        //前端通过微信官方接口 获得的code，然后通过code获取openid 和sessionkey
//        String urlPath = String.format(Constants.APP_CODE2_OPENID_URL, driverAppRegisterProp.getAppId(), driverAppRegisterProp.getSecretKey(), appRegisterCode);
//        String response = HttpUtil.get(urlPath);
//        //获得的sessionkey和openid转化为对象
//        WxCode2OpenId code2OpenId = JSONUtil.toBean(response, WxCode2OpenId.class);
//        String openId = code2OpenId.getOpenid();
//        System.out.println(openId);
//        AssertUtil.isNotNull(openId, GlobalExceptionCode.PARAM_CODE_ERROR);

        String openId = wechatTemplate.getOpenId(appRegisterCode);

        //判断用户是否注册过
        Driver driver = super.getOne(new LambdaQueryWrapper<Driver>().eq(Driver::getOpenId, openId));
        AssertUtil.isNull(driver,GlobalExceptionCode.PARAM_PHONE_EXIST);
        Driver saveAppDriver = saveAppDriver(openId);
        //初始化主键相同的其他关联表
        initDriverSetting(saveAppDriver.getId());
        initDriverSummery(saveAppDriver.getId());
        initDriverWallet(saveAppDriver.getId());

        //保存login对象
        AppLoginApiParam appLoginApiParam = new AppLoginApiParam();
        appLoginApiParam.setId(saveAppDriver.getId());
        appLoginApiParam.setType(1);
        appLoginApiParam.setAdmin(false);
        appLoginApiParam.setAvatar(Constants.AVATAR_URL);
        appLoginApiParam.setNickName(NameUtil.getName());
        appLoginApiParam.setOpenId(openId);
        appLoginApiParam.setPhone(saveAppDriver.getPhone());
        R<Boolean> result = appLoginApi.appLogin(appLoginApiParam);
        AssertUtil.isTrue(result.isSuccess(),GlobalExceptionCode.SERVICE_ERROR);
    }


    //这个方法只有企业小程序才能使用->获取微信用户手机号
    private String getPhoneNumber(){
        return null;
    }


    private void initDriverWallet(Long driverId) {
        DriverWallet driverWallet = new DriverWallet();
        driverWallet.setId(driverId);
        driverWallet.setAmount(BigDecimal.ZERO);
        driverWallet.setCreateTime(new Date());
        //生成随机密码，阿里云 发短信给用户 TODO
        String pwd = RandomUtil.randomString(8);
        driverWallet.setPassword(pwd);
        driverWalletService.save(driverWallet);

    }

    private void initDriverSummery(Long driverId) {
        DriverSummary driverSummary = new DriverSummary();
        driverSummary.setId(driverId);
        driverSummary.setLevel(Constants.RealAuth.VERIFYING);
        driverSummary.setTotalOrders(0);
        driverSummary.setWeekOrders(0);
        driverSummary.setGoodComments(0);
        driverSummary.setAppeal(0);
        driverSummary.setTotalComplaint(0);
        driverSummary.setTodayTotalCancel(0);
        driverSummary.setDriveDuration(0);
        driverSummary.setTradeOrders(0);
        driverSummary.setTodayTradeOrders(0);
        driverSummary.setTodayComplaint(0);
        driverSummary.setTodayCancel(0);
        driverSummary.setTodayIncome(BigDecimal.ZERO);
        driverSummary.setCreateTime(new Date());
        driverSummaryService.save(driverSummary);

    }

    private void initDriverSetting(Long driverId) {
        DriverSetting driverSetting = new DriverSetting();
        driverSetting.setId(driverId);
        driverSetting.setAutoAccept(false);
        driverSetting.setOrientation(false);
        driverSetting.setListenService(false);
        driverSetting.setOrderDistance(50);
        driverSetting.setRangeDistance(50);
        driverSetting.setCreateTime(new Date());
        driverSettingService.save(driverSetting);

    }

    private Driver saveAppDriver(String openid) {
        Driver driver = new Driver();
        String s2 = RandomUtil.randomNumbers(1);
        String nums = RandomUtil.randomNumbers(9);
        driver.setPhone("1"+s2+ nums);
        driver.setCreateTime(new Date());
        driver.setOpenId(openid);
        driver.setBitState(BitStatesUtil.OP_PHONE);
        super.save(driver);
        return driver;

    }
}
